import axios from 'axios';
import {nanoid} from 'nanoid';
import Vue from 'vue'

import Vuex from 'vuex'

// 通过Vue加载这个插件
Vue.use(Vuex)

const actions = {
    jia(store,value){
        // console.log("add的dispatch被触发了",store,value);
        store.commit("JIA",value);
    },
    jian(store,value){
        store.commit("JIAN",value);
    },
    oddAdd(store,value){
        store.commit("ODDADD",value);
    },
    waitAdd(store,value){
        store.commit("WAITADD",value);
    },

    addPersonXW(store,value){
        if(value[0] === '王'){
            store.commit("ADDPERSON",value);
        }else{
            alert("只能添加姓王的人")
        }
    },
    addRandomPerson(store,value){
        axios.get('https://api.xygeng.cn/one').then(
            res=>{
                //console.log(res.data.data.content);
                let context = res.data.data.content;
                store.commit("ADDPERSON",context);
            }
        )
    }

}

const mutations = {
    JIA(state,value){
        // console.log("add的commit被触发了",a,b);
        state.count += value
    },
    JIAN(state,value){
        state.count -= value
    },
    ODDADD(state,value){
        if(state.count % 2 != 0){
            state.count += value
        }
    },
    WAITADD(state,value){
        setTimeout(()=>{
            state.count += value
        },500)
    },

    ADDPERSON(state,value){
        this.state.personList.unshift({id:nanoid(),name:value})
    },

    
}

const state = {
    count:0,
    studentName:'学生名称',
    schoolName:'二圣小学',
    smallName:'xfj',
    personList:[{id:'001',name:'张三'}]
}

const getters = {
    ncount(){
        return state.count * 10
    }
}


export default new Vuex.Store({
    actions,
    mutations,
    state,
    getters
})